package cn.wolfcode.shiro;

import cn.wolfcode.domain.Employee;
import cn.wolfcode.domain.Role;
import cn.wolfcode.service.IEmployeeService;
import cn.wolfcode.service.IPermissionService;
import cn.wolfcode.service.IRoleService;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.AuthenticationException;
import org.apache.shiro.authc.AuthenticationInfo;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.authc.SimpleAuthenticationInfo;
import org.apache.shiro.authz.AuthorizationInfo;
import org.apache.shiro.authz.SimpleAuthorizationInfo;
import org.apache.shiro.realm.AuthorizingRealm;
import org.apache.shiro.subject.PrincipalCollection;
import org.apache.shiro.subject.Subject;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.List;

/**
 * 用户登录与授权realm
 */
public class CarBusinessRealm extends AuthorizingRealm {

    @Autowired
    private IEmployeeService employeeService;

    @Autowired
    private IRoleService roleService;

    @Autowired
    private IPermissionService permissionService;





    @Override
    protected AuthenticationInfo doGetAuthenticationInfo(AuthenticationToken token) throws AuthenticationException {
        //获取用户名
        String username = (String) token.getPrincipal();
        //以用户名作为条件查询用户对象
        Employee employee = employeeService.selectByUsername(username);
        //封装认证info对象
        if (employee != null){
            return new SimpleAuthenticationInfo(username,employee.getPassword(),this.getName());
        }

        return null;
    }

    @Override
    protected AuthorizationInfo doGetAuthorizationInfo(PrincipalCollection principals) {

        SimpleAuthorizationInfo info = new SimpleAuthorizationInfo();

        //1:获取当前登录用户对象
        Employee employee = (Employee) principals.getPrimaryPrincipal();

        //2:以当前登录用户对象id为条件,查询当前登录用户拥有角色与权限
        List<String> roles = roleService.queryByEmpId(employee.getId());
        List<String> exps = permissionService.selectByEmpId(employee.getId());
        //如果用户是超级管理员
        if (employee.isAdmin()){
            //设置超级管理员角色
            info.addRole(employee.getUsername());
            //设置超级管理员权限
            info.addStringPermission("*:*");
        }else {
            //3:将角色与权限封装成授权info对象
            info.addRoles(roles);
            info.addStringPermissions(exps);
        }
        return info;
    }


}
